const app = getApp()

import axios from '../../utils/axios'

Page({

  data: {
    useCoupon: false, // 优惠券模态框
    shoppList: [], // 上一个页面缓存的商品
    cartsId: '', // 所有商品id，逗号隔开
    sumMoney: '', // 合计价格
    usableCoupon: '0张可用', // 几张优惠券可用
    couponList: [], // 用户优惠券list
    couponId: '', // 使用的优惠券ID
    denomination: 0, // 优惠券使用的金额
    realityMoney: 0, // 实付价格
    message: '', // 买家留言
    address: {
      userName: '',
      userPhone: '',
      province: '',
      details: '',
      contactId: '',
      postcode: ''
    }, // 地址
    count: 0, // 直接购买的数量
    paymentParam: {}, // 支付参数
    eventInfo: '', // 记录当前的事件
    sendCost: 0, // 运费
    fullFree: 0, // 满多少免运费
  },

  onLoad: function (options) {

    this.setData({
      count: options.count,
      shoppList: wx.getStorageSync('shoppList')
    })

    // 获取用户之前选择过的地址
    this.getUserAddress()

    // 计算商品list
    this.calculateList()

    // 查询用户可用优惠券
    this.mayCoupon()

    // 获取运费
    this.carriage()

  },

  onShow: function () {

    if (app.globalData.showAddress) {

      app.globalData.showAddress = false

      let address = wx.getStorageSync('address')

      this.setData({
        'address.userName': address.contacts,
        'address.userPhone': address.phone,
        'address.province': address.address,
        'address.details': address.detail_address,
        'address.contactId': address.id,
        'address.postcode': address.postal_code
      })

    }

  },

  // 登录，事件委托
  getUserInfo: function (e) {
    // 当接口返回‘请登录’时，showLogin就变为true，然后调用授权
    if (e.detail.userInfo && app.globalData.showLogin) {
      const self = this
      app.signin(e.detail, function (res) {
        app.globalData.showLogin = false

        self.mayCoupon()
        // 当事件是点击收货地址
        if (self.data.eventInfo == "address") {
          wx.navigateTo({
            url: '/pages/address/address',
          })
        } else if (self.data.eventInfo == "coupon") {
          self.setData({
            useCoupon: true
          })
        } else if (self.data.eventInfo == "payment") {
          self.orderGoods()
        }
      })
    }
  },

  // 读取用户上次选择地址的缓存
  getUserAddress: function () {
    const self = this
    wx.getStorage({
      key: 'address',
      success(res) {
        console.log(res)
        self.setData({
          'address.userName': res.data.contacts,
          'address.userPhone': res.data.phone,
          'address.province': res.data.address,
          'address.details': res.data.detail_address,
          'address.contactId': res.data.id,
          'address.postcode': res.data.postal_code
        })
      }
    })
  },

  // 选择地址
  pitchAddress: function (e) {

    if (app.globalData.showLogin) {
      // 事件统一委托到getUserInfo
      this.setData({
        eventInfo: 'address'
      })
    } else {
      wx.navigateTo({
        url: '/pages/address/address',
      })
    }

  },

  // 使用优惠券
  employCoupon: function (e) {
    console.log(e)

    const self = this

    let denomination = parseFloat(e.currentTarget.dataset.denomination)

    // 先把之前使用过的加到总价
    this.setData({
      realityMoney: parseFloat(parseFloat(this.data.realityMoney) + this.data.denomination).toFixed(2),
    })

    setTimeout(() => {
      self.setData({
        couponId: e.currentTarget.dataset.couponid,
        realityMoney: parseFloat(parseFloat(self.data.realityMoney) - denomination).toFixed(2),
        denomination: denomination,
        usableCoupon: '已优惠' + denomination + '元',
        useCoupon: false
      })
    }, 10)

  },

  // 不使用优惠券
  notCoupon: function (e) {

    this.setData({
      couponId: '',
      realityMoney: parseFloat(parseFloat(this.data.realityMoney) + this.data.denomination).toFixed(2),
      denomination: 0,
      usableCoupon: '已优惠0.00元',
      useCoupon: false
    })

  },

  // 提交订单
  orderGoods: function (e) {

    const self = this

    this.setData({
      eventInfo: 'payment'
    })

    let paramJson = {
      contact_id: this.data.address.contactId,
      type: "groupon"
    }

    if (this.data.count) {
      paramJson['attach_id'] = this.data.shoppList[0].attach_id
      paramJson['goods_num'] = this.data.shoppList[0].num
      paramJson['goods_id'] = this.data.shoppList[0].goods_id
    } else {
      paramJson['cart_id'] = this.data.cartsId
    }

    if (this.data.couponId) {
      paramJson['coupon_id'] = this.data.couponId
    }

    if (this.data.message) {
      paramJson['message'] = this.data.message
    }

    axios('/groupon/orderGoods', paramJson).then(res => {
      console.log(res)
      if (res.data.resultcode == 1) {

        if (res.data.result.jsApiParameters == undefined) {
          wx.redirectTo({
            url: '/pages/orderInfo/orderInfo'
          })
        } else {

          this.setData({
            jsApiParameters: res.data.result
          })

          let payment = JSON.parse(res.data.result.jsApiParameters)

          wx.requestPayment({
            nonceStr: payment.nonceStr,
            package: payment.package,
            paySign: payment.paySign,
            timeStamp: payment.timeStamp,
            signType: payment.signType,
            success(pay) {
              wx.showToast({
                title: '支付成功',
                icon: 'none',
                duration: 1000
              })
              setTimeout(function () {
                wx.redirectTo({
                  url: '/pages/orderInfo/orderInfo'
                })
              }, 1000)

            },
            fail: err => {
              wx.setStorageSync('paymentAddress', self.data.address)
              wx.redirectTo({
                url: '/pages/payment/payment?denomination=' + this.data.denomination + '&orderId=' + res.data.result.order_id + "&createTime=" + res.data.result.create_time + "&orderNum=" + res.data.result.order_num,
              })
            }
          })

        }

      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 1300
        })
      }
    })

  },

  carriage: function () {
    axios('/groupon/setting').then(res => {
      console.log(res)
      if (res.data.resultcode == 1) {

        let full = parseFloat(res.data.result.full_free)

        let send = parseFloat(res.data.result.send_cost)

        let fullFree = ''

        if (parseFloat(this.data.sumMoney) > full) {
          fullFree = '满包邮'
        } else {
          this.setData({
            realityMoney: parseFloat(parseFloat(this.data.realityMoney) + send).toFixed(2)
          })
          fullFree = '+¥' + parseFloat(send).toFixed(2)
        }

        this.setData({
          sendCost: send,
          fullFree: fullFree
        })
      }
    })
  },

  // 根据cartId查看几张优惠券可用
  mayCoupon: function () {

    let paramJson = {
      store_id: app.globalData.storeId,
    }

    if (this.data.count) {
      paramJson['goods_id'] = this.data.shoppList[0].goods_id
      paramJson['num'] = this.data.shoppList[0].num
    } else {
      paramJson['carts_id'] = this.data.cartsId
    }

    axios('/personal/coupons', paramJson).then(res => {
      console.log(res)
      if (res.data.resultcode == 1) {

        let list = res.data.result.list

        let usable = 0

        // 可以领取的放在前面
        let useList = []
        let notList = []

        for (let i = 0; i < list.length; i++) {

          list[i]['use'] = false

          if (list[i].status == 1 && parseFloat(this.data.sumMoney) >= parseFloat(list[i].start_point)) {
            usable++
            list[i].use = true
            useList.push(list[i])
          } else {
            notList.push(list[i])
          }

        }

        this.setData({
          usableCoupon: usable == 0 ? '0张可用' : usable + '张可用',
          couponList: useList.concat(notList)
        })
      }
    })

  },

  // 处理商品list
  calculateList: function () {

    let list = this.data.shoppList

    let sumMoney = 0

    let cartsId = ''

    for (let i = 0; i < list.length; i++) {

      cartsId += list[i].cart_id

      if (i != list.length - 1) {
        cartsId += ','
      }

      sumMoney += parseFloat(list[i].showCount)

    }

    this.setData({
      cartsId: cartsId,
      realityMoney: parseFloat(sumMoney).toFixed(2),
      sumMoney: parseFloat(sumMoney).toFixed(2)
    })

  },

  // 买家输入留言事件
  messageInput: function (e) {
    this.setData({
      message: e.detail.value
    })
  },

  // 关闭使用优惠券模态框
  closeCoupon: function () {
    this.setData({
      useCoupon: false
    })
  },

  // 阻止优惠券模态框事件冒泡，此方法不能删
  stopCoupon: function () { },

  // 打开使用优惠券模态框
  openCoupon: function () {
    if (app.globalData.showLogin) {
      this.setData({
        eventInfo: "coupon"
      })
    } else {
      this.setData({
        useCoupon: true
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})